<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'

//文章分类数据模型
const categorys = ref([
    {
        "id": 3,
        "categoryName": "",
        "categoryAlias": "m",
        "createTime": "",
        "updateTime": ""
    }
])

//用户搜索时选中的分类id
const categoryId=ref('')

//用户搜索时选中的发布状态
const state=ref('')

//文章列表数据模型
const articles = ref([
    {
        "id": 5,
        "title": "",
        "content": "",
        "coverImg": "",
        "state": "",
        "categoryId": 2,
        "createTime": "",
        "updateTime": "",
        "studentId": '',
        "name": '',
        "score": '',
        "timeTaken": ''
    }
])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    articleList();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    articleList();
}

//调用article.js后台接口
import {articleCategoryListService,articleListeService,articleAddService,articleUpdateService,articleDeleteService} from '@/api/article.js'
const articleCategoryList =async()=>{
    let result = await articleCategoryListService();

    categorys.value = result.data
}
articleCategoryList();


//获取文章列表数据
const articleList = async()=>{
    let params = {
        pageNum:pageNum.value,
        pageSize:pageSize.value,
        categoryId:categoryId.value? categoryId.value : null,
        state:state.value? state.value : null
    }
   let result = await articleListeService(params);

   //渲染视图
   total.value = result.data.total;
   articles.value = result.data.items;


   //处理数据,给数据模型扩展一个属性categoryName，分类名称
   for(let i=0;i<articles.value.length;i++){
    let article = articles.value[i];
        for(let j=0;j<categorys.value.length;j++){
           if(article.categoryId == categorys.value[j].id) {
            article.categoryName = categorys.value[j].categoryName
           }
        }
   }
}
articleList();

import {Plus} from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElDialog,ElMessageBox } from 'element-plus'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref({
    title: '',
    categoryId: '',
    coverImg: '',
    content:'',
    state:'',
    studentId: '',
    name: '',
    score: '',
    timeTaken: ''
})

//导入token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore();

//上传成功回调函数
const uploadSuccess = (result) => {
    articleModel.value.coverImg = result.data;
    console.log(result);

}
//添加文章
const addArticle = async(clickState) => {
    //把发布的状态赋值给数据模型
    articleModel.value.state = clickState;
    //调用后台接口
    let result = await articleAddService(articleModel.value);    
    
    ElMessage.success(result.msg? result.msg : '添加成功');

    //关闭抽屉
    visibleDrawer.value = false;

    //刷新文章列表    
    articleList();
}

//预览大图
const previewImg = (imgUrl) => {
    dialogImg.value = imgUrl;
    imgDialogVisible.value = true;
    //打印图片地址
console.log(dialogImg.value)
}
//下载图片
const downloadImg = (imgUrl) => {
    window.open(imgUrl)
}
const imgDialogVisible = ref(false)
const dialogImg = ref('')

//定义变量，控制标题的展示
const title = ref('')
//展示编辑弹窗
const showDialog = (row)=>{
    visibleDrawer.value = true;
    title.value = '编辑成绩'
    //数据拷贝
    articleModel.value = JSON.parse(JSON.stringify(row))
    //给分类名称赋值
    articleModel.value.categoryName = row.categoryName
    //扩展id属性，将来需要传递给后台，完成分类修改
    articleModel.value.id = row.id 
}
//修改文章
const updateArticle = async(clickState) => {
    //调用后台接口
     //把发布的状态赋值给数据模型
     articleModel.value.state = clickState;
    let result = await articleUpdateService(articleModel.value);
    ElMessage.success(result.msg? result.msg : '修改成功');

    //关闭抽屉
    visibleDrawer.value = false;

    //刷新文章列表    
    articleList();
}
//清空表单数据
const clearAddData = () => {
    articleModel.value = {
        title: '',
        categoryId: '',
        coverImg: '',
        content:'',
        state:''
    }
}
//删除信息
const deleteScore =(row)=>{
    //提示用户确认框
    ElMessageBox.confirm(
    '你确认要删除该信息吗?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
        //调用接口
       let result = await articleDeleteService(row.id);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //刷新文章列表    
    articleList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>成绩管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer=true;title='添加成绩';clearAddData()">手动添加</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="成绩分类：">
                <el-select placeholder="请选择" v-model="categoryId" style="width: 240px;">
                    <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 240px;">
                    <el-option label="已审核" value="已审核"></el-option>
                    <el-option label="未审核" value="未审核"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="articleList">搜索</el-button>
                <el-button @click="categoryId='';state=''">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="articles" style="width: 100%">
            <el-table-column label="学号" width="150px" prop="studentId"></el-table-column>
            <el-table-column label="姓名" width="120px" prop="name"></el-table-column>
            <el-table-column label="成绩" width="120px" prop="score"></el-table-column>
            <el-table-column label="作答时间" width="120px" prop="timeTaken"></el-table-column>
            <el-table-column label="分类" prop="categoryName" width="130px"></el-table-column>
            <el-table-column label="上传时间" prop="createTime" width="150px"> </el-table-column>
            <el-table-column label="状态" prop="state"></el-table-column>
            //增加一个显示文章图片的列，绑定数据为coverImg，并显示封面图片，点击图片可预览大图
            <el-table-column label="成绩图片" width="200px">
                <template #default="{ row }">
                    <img :src="row.coverImg" style="width: 100px; height: 80px; cursor: pointer" @click="previewImg(row.coverImg)">
                    <el-button type="text" size="mini" style="margin-left: 10px" @click="downloadImg(row.coverImg)">下载</el-button>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="100px">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" style="margin-right: 10px" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteScore(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="学号">
                    <el-input v-model="articleModel.studentId" placeholder="请输入学号"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="articleModel.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="成绩">
                    <el-input v-model="articleModel.score" placeholder="请输入成绩"></el-input>
                </el-form-item>
                <el-form-item label="作答时间">
                    <el-input v-model="articleModel.timeTaken" placeholder="请输入作答时间"></el-input>
                </el-form-item>
                <el-form-item label="成绩分类">
                    <el-select placeholder="请选择" v-model="articleModel.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="成绩图">
                    <!-- 
                        auto-upload="false" 禁止自动上传，否则会导致图片上传失败
                        action:设置服务器接口路径
                        name:设置上传的文件字段名
                        headers:设置请求头
                        on-success:上传成功回调函数
                     -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                        action="/api/upload" 
                        name="file" 
                        :headers="{'Authorization':tokenStore.token}" 
                        :on-success="uploadSuccess">
                        <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="批注">
                    <div class="editor">
                        <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                        </quill-editor>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="title=='添加成绩'?addArticle('已审核'): updateArticle('已审核')">已审核</el-button>
                    <el-button type="info" @click="title=='添加成绩'?addArticle('未审核'): updateArticle('未审核')">未审核</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <!-- 预览大图弹窗 -->
        <el-dialog v-model="imgDialogVisible" title="预览大图">
            <img :src="dialogImg" style="width: 100%; height: 100%;" />
            <div style="text-align: center; margin-top: 20px;">
                <el-button type="primary" size="small" @click="downloadImg">下载图片</el-button>
            </div>
        </el-dialog>
    </el-card>
</template>
<style lang="scss" scoped>

/* 全局样式 */
.el-card {
    margin-bottom: 20px;
}

.el-form-item {
    margin-bottom: 20px;
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>